<template>
  <div class="search-suggestion">
    <van-cell icon="search"
              v-for="(text, index) in suggestionList"
              :key="index"
              @click="$emit('search', text)">
      <div slot="title"
           v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestionList: []
    }
  },
  watch: {
    searchText: {
      immediate: true,
      handler: debounce(function (value) {
        this.loadSearchSuggestion(value)
      }, 1000)
    }
  },
  methods: {
    async loadSearchSuggestion (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestionList = data.data.options
      } catch (err) {
        this.$toast('数据获取失败，请稍后重试')
      }
    },
    highlight (text) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      text = text.replace(reg, highlightStr)
      return text
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/span.active {
    color: #3296fa;
  }
}
</style>
